﻿using System;
using System.Text;
using System.Collections.Generic;
using Communication.Packets;
using ConnectServer;
using System.IO;
using Utilities.IO;
using Utilities.Conversion;

namespace ConnectServer.Protocol
{
    /// <summary>
    /// ServerInfo packet.
    /// </summary>
    public sealed class ServerInfoPacket : ConnectServerPacket
    {
        public new static int ID = 0x03;

        #region Ctor

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="groupId">requested server's group id</param>
        /// <param name="serverId">requested server's id</param>
        public ServerInfoPacket(int groupId, int serverId)
            : base(PacketType.C1, ID)
        {
            this.m_serverGroups = Config.Instance.Groups;
            this.m_groupId = groupId;
            this.m_serverId = serverId;
        }
        #endregion

        #region Serialization & Deserialization

        public ServerInfoPacket(BufferedStream buffer)
            : base(buffer)
        {
            // check if this is the right packet type.
            if (this.m_subId != ID)
            {
                throw new InvalidPacketIDError();
            }
            EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, buffer);
            this.m_groupId = reader.ReadByte();
            this.m_serverId = reader.ReadByte();
            this.m_serverGroups = Config.Instance.Groups;
        }

        public override void Serialize(BufferedStream buffer)
        {
            EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Big, buffer);
            Config.Server server = getServerById(m_groupId, m_serverId);
            writer.Write(server.IP, 16);
            writer.Write((short)server.Port);
            base.Serialize(buffer);

            //TODO: elegant way.
            buffer.Seek(0, SeekOrigin.Begin);
        }
        #endregion

        #region Privates
        private Config.Server getServerById(int groupId, int serverId)
        {
            return this.m_serverGroups[groupId].Servers[serverId];
        }
        #endregion

        #region Fields
        private List<Config.ServerGroup> m_serverGroups;
        private int m_groupId;
        private int m_serverId;
        #endregion
    }
}
